package com.chaos.auth.config.userdetails;

import cn.hutool.core.util.ObjectUtil;
import com.chaos.auth.config.userdetails.AdminUserDetails;

import com.chaos.auth.data.RbacUserData;
import com.chaos.auth.service.RbacUserService;
import com.chaos.framework.model.dto.result.list.ListResult;
import com.chaos.framework.starter.helper.ResultHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AdminDetailsService {
    @Resource
    private RbacUserService rbacUserService;

    public RbacUserData getRbacUserDtoByPhone(String phone, Long tenantId) {
        RbacUserData query = RbacUserData.builder().build();
        return getRbacUserData(query);
    }

    public RbacUserData getRbacUserDtoByUsername(String username, Long tenantId) {
        RbacUserData query = RbacUserData.builder().username(username).build();
        return getRbacUserData(query);
    }

    public RbacUserData getRbacUserDtoByUsername(String username) {
        return getRbacUserData(RbacUserData.builder().username(username).build());
    }

    private RbacUserData getRbacUserData(RbacUserData queryData) {
        List<RbacUserData> RbacUserDtos = rbacUserService.selectByData(queryData);
        if (ObjectUtil.isEmpty(RbacUserDtos)) {
            throw new DisabledException("用户不存在");
        }
        if (RbacUserDtos.size() > 1) {
            throw new DisabledException("用户名异常");
        }
        return RbacUserDtos.get(0);
    }

    public AdminUserDetails getAdminUserDetails(RbacUserData rbacUser) {
//        Set<Long> roles = rbacUserRoleService.selectRolesByUserId(rbacUser.getId(),rbacUser.getTenantId());
//        if (ObjectUtil.isEmpty(roles)) {
//            throw new DisabledException("该账户无有效权限!");
//        }
        AdminUserDetails userDetails = new AdminUserDetails(rbacUser);
//        if (!userDetails.isEnabled()) {
//            throw new DisabledException("该账户已被禁用!");
//        } else if (!userDetails.isAccountNonLocked()) {
//            throw new LockedException("该账号已被锁定!");
//        } else if (!userDetails.isAccountNonExpired()) {
//            throw new AccountExpiredException("该账号已过期!");
//        }

        return userDetails;

    }


}
